package oracle.apps.financials.collection.activity;

import greendroid.widget.PageIndicator;
import greendroid.widget.PagedView;
import greendroid.widget.PagedView.OnPagedViewChangeListener;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import oracle.apps.financials.collection.LoadDataAsyncTask;
import oracle.apps.financials.collection.adapter.ItemAdapter;
import oracle.apps.financials.collection.fragment.BaseGraphFragment;
import oracle.apps.financials.collection.fragment.CEIGraphFragment;
import oracle.apps.financials.collection.fragment.DSOGraphFragment;
import oracle.apps.financials.collection.fragment.PercentCurrentGraphFragment;
import oracle.apps.financials.collection.listener.BaseOnClickListener;
import oracle.apps.financials.collection.listener.CallActionListener;
import oracle.apps.financials.collection.listener.CollectorPopupWindowListener;
import oracle.apps.financials.collection.listener.CustomerDetailPopupWindowListener;
import oracle.apps.financials.collection.listener.NotePopupWindowListener;
import oracle.apps.financials.collection.listener.SearchTopDelinquentPopupWindowListener;
import oracle.apps.financials.collection.po.ColorTextItem;
import oracle.apps.financials.collection.po.Customer;
import oracle.apps.financials.collection.po.Item;
import oracle.apps.financials.collection.po.MetricDetailItem;
import oracle.apps.financials.collection.po.MetricsItem;
import oracle.apps.financials.collection.po.ThumbnailItem;
import oracle.apps.financials.collection.po.TitleItem;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cyrilmottier.android.greendroid.R;

public class TopDelinquentCustomerActivity extends BaseListActivity {

	protected HashMap<String, BaseGraphFragment> graphFragmentList = new HashMap<String, BaseGraphFragment>();
	protected PageIndicator mPageIndicatorOther;
	protected ItemAdapter metricsItemAdapter;
	protected CollectorPopupWindowListener collectorPopupWindowListener;
	protected List<BaseOnClickListener> listenerList = new ArrayList<BaseOnClickListener>();
	protected Context context;
	protected LoadDataAsyncTask loadDataAsyncTask;
	protected List<Customer> topDelinquentCustomerList;

	private final Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (msg.obj != null) {
					customer = (Customer) msg.obj;
				}
				TopDelinquentCustomerActivity.this.refreshView();
				break;
			}
			super.handleMessage(msg);
		}
	};

	public void refreshView() {

		TextView customerName = (TextView) this.findViewById(R.id.customer_name);
		customerName.setText(customer.getCustomerName());
		metricsItemAdapter.resetAdapter(this.getMetricsItemList(customer));
		for (BaseOnClickListener popupWindow : listenerList) {
			popupWindow.refreshData(customer);
		}

		graphFragment.refreshGraphView(customer);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		loadDataAsyncTask = new LoadDataAsyncTask(this, this.mHandler, R.string.loading, R.string.loading_fail, getDatabaseHelper());
		loadDataAsyncTask.execute();

		setContentView(R.layout.top_delinquent_customer);

		initCustomer();

		intitMenuBarAndGraphFragment(customer);

		initFragments(customer);

		processActionButtonEvent();

		metricsItemAdapter = new ItemAdapter(this, getMetricsItemList(customer));

		setListAdapter(metricsItemAdapter);

		initGraphView(graphFragmentList.get(PercentCurrentGraphFragment.class.getSimpleName()));

	}

	public void initCustomer() {
		if (customer == null) {

			try {
				topDelinquentCustomerList = getDatabaseHelper().getCustomerDao().queryForAll();
				if (topDelinquentCustomerList != null) {
					for (Customer customer : topDelinquentCustomerList) {
						String[] result = getDatabaseHelper()
								.getMetricsItemDao()
								.queryRaw(
										"select max(metricsItemID) from c_metrics_item where " + Customer.CUSTOMER_ID + "="
												+ customer.getCustomerID()).getFirstResult();
						if (result.length > 0 && result[0] != null) {
							List<MetricsItem> items = getDatabaseHelper().getMetricsItemDao().queryForEq(MetricsItem.METRICS_ITEM_ID,
									Integer.valueOf(result[0]));
							if (!items.isEmpty()) {
								customer.setCurrentMetricsItem(items.get(0));
							}
						}
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

			customer = topDelinquentCustomerList == null || topDelinquentCustomerList.isEmpty() ? new Customer() : topDelinquentCustomerList.get(0);

		}
	}

	protected void initFragments(Customer customer) {
		graphFragmentList.put(BaseGraphFragment.class.getSimpleName(), graphFragment);
		graphFragmentList.put(PercentCurrentGraphFragment.class.getSimpleName(), new PercentCurrentGraphFragment(customer, mHandler));
		graphFragmentList.put(CEIGraphFragment.class.getSimpleName(), new CEIGraphFragment(customer, mHandler));
		graphFragmentList.put(DSOGraphFragment.class.getSimpleName(), new DSOGraphFragment(customer));

	}

	protected void initGraphView(Fragment fragment) {
		FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
		fragmentTransaction.replace(R.id.graph_area, fragment);
		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.commit();
		this.graphFragment = (BaseGraphFragment) fragment;
	}

	protected OnPagedViewChangeListener mOnPagedViewChangedListener = new OnPagedViewChangeListener() {

		@Override
		public void onStopTracking(PagedView pagedView) {
		}

		@Override
		public void onStartTracking(PagedView pagedView) {
		}

		@Override
		public void onPageChanged(PagedView pagedView, int previousPage, int newPage) {
			mPageIndicatorOther.setActiveDot(newPage);
		}
	};

	public void processActionButtonEvent() {

		TextView customerName = (TextView) this.findViewById(R.id.customer_name);
		customerName.setText(customer.getCustomerName());

		// Button searchButton = (Button)
		// findViewById(R.id.search_top_delinquent_customer);
		BaseOnClickListener searchListener = new SearchTopDelinquentPopupWindowListener(this, topDelinquentCustomerList, mHandler);
		listenerList.add(searchListener);

		customerName.setOnClickListener(searchListener);
		// searchButton.setOnClickListener(searchListener);

		Button callButton = (Button) findViewById(R.id.call_button);
		BaseOnClickListener callActionListener = new CallActionListener(this, customer);
		listenerList.add(callActionListener);
		callButton.setOnClickListener(callActionListener);

		Button noteButton = (Button) findViewById(R.id.note_button);
		BaseOnClickListener noteListener = new NotePopupWindowListener(this, customer);
		listenerList.add(noteListener);
		noteButton.setOnClickListener(noteListener);

		Button detailButton = (Button) findViewById(R.id.detail_button);
		BaseOnClickListener customerDetailListener = new CustomerDetailPopupWindowListener(this, customer);
		listenerList.add(customerDetailListener);
		detailButton.setOnClickListener(customerDetailListener);

		collectorPopupWindowListener = new CollectorPopupWindowListener(this, customer, mHandler);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.context = null;
	}

	@Override
	protected void onListItemClick(ListView list, View v, int position, long id) {

		BaseGraphFragment graphFragment = null;
		if (position == 4 || position == 5 || position == 6) {
			graphFragment = graphFragmentList.get(DSOGraphFragment.class.getSimpleName());

		} else if (position == 3) {
			graphFragment = graphFragmentList.get(CEIGraphFragment.class.getSimpleName());

		} else if (position == 9 || position == 10) {
			graphFragment = graphFragmentList.get(PercentCurrentGraphFragment.class.getSimpleName());

		}
		Toast.makeText(this, "you click the postion " + position, Toast.LENGTH_SHORT).show();
		if (graphFragment != null) {
			graphFragment.refreshGraphView(customer);
			initGraphView(graphFragment);
		}

		metricsItemAdapter.setHighlight(position);

	}

	public List<Item> getMetricsItemList(Customer customer) {

		List<Item> items = new ArrayList<Item>();
		items.add(new TitleItem("Collector"));

		collectorPopupWindowListener.setCustomer(customer);
		if (customer.getCollector() != null) {

			items.add(new ThumbnailItem(customer.getCollector().getCollectorName(), "CEI: " + customer.getCollector().getCEI(), R.drawable.class1,
					collectorPopupWindowListener));
		}

		MetricsItem metricsItem = customer.getCurrentMetricsItem();
		items.add(new TitleItem("Metrics", Color.rgb(74, 74, 74)));

		items.add(new MetricDetailItem("Net Balance: " + metricsItem.getNetBalance() + " " + metricsItem.getCurrency(), false));
		items.add(new MetricDetailItem("Account Overdue: " + metricsItem.getAccountOverdue() + " " + metricsItem.getCurrency(), false));
		items.add(new MetricDetailItem("Days Sales Outstanding: " + metricsItem.getDaysSalesOutstanding()));
		items.add(new MetricDetailItem("Best Possible DSO: " + metricsItem.getBestPossibleDSO(), false));

		items.add(new ColorTextItem("Sales Weighted DSO: ", metricsItem.getSalesWeightedDSO() + "", " (AVG:" + metricsItem.getSalesWeightedDSOAvg()
				+ ")", metricsItem.getSalesWeightedDSO() > metricsItem.getSalesWeightedDSOAvg() ? Color.RED : Color.GREEN));

		items.add(new MetricDetailItem("True DSO:  " + metricsItem.getTrueDSO()));
		items.add(new MetricDetailItem("Strategy Effectiveness: " + metricsItem.getStrategyEffectiveness(), false));
		MetricDetailItem percentCurrentMetricDetailItem = new MetricDetailItem("Percent Current:  " + metricsItem.getPercentCurrent());
		percentCurrentMetricDetailItem.setHighlight(true);
		items.add(percentCurrentMetricDetailItem);

		items.add(new ColorTextItem("Percent 91 + Days Delinqent:  ", metricsItem.getPercent90OverDaysDelinquent() + "", " (AVG:"
				+ metricsItem.getPercent90OverDaysDelinquentAvg() + ")", metricsItem.getPercent90OverDaysDelinquent() > metricsItem
				.getPercent90OverDaysDelinquentAvg() ? Color.RED : Color.GREEN, false));

		items.add(new MetricDetailItem("Average Days Late :  " + metricsItem.getAverageDaysLate()));
		items.add(new MetricDetailItem("Weighted Average Days Late:  " + metricsItem.getWeightedAverageDaysLate(), false));
		items.add(new MetricDetailItem("Total Receipt :  " + metricsItem.getTotalReceipt()));
		items.add(new MetricDetailItem("Weighted Average Days Paid:  " + metricsItem.getWeightedAverageDaysPaid(), false));
		return items;
	}

}
